package com.chinackts.common.utils;

import org.joda.time.DateTime;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author Lianhong
 * @since 2021/10/29
 * 开始结束日期按月分割
 */
public class MonthDivider {

    /**
     * 开始结束日期按月分割，生成新的日期列表
     * 格式 yyyy-MM-dd
     */
    public static List<String[]> divide(String beginDate, String endDate) throws ParseException {
        DateFormat format = new SimpleDateFormat("yyyy-MM");

        Calendar min = Calendar.getInstance();
        min.setTime(format.parse(beginDate));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        Calendar max = Calendar.getInstance();
        max.setTime(format.parse(endDate));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        //月份分割
        List<String> months = new ArrayList<>();
        while (min.before(max)) {
            months.add(format.format(min.getTime()));
            min.add(Calendar.MONTH, 1);
        }
        //日期分割
        List<String[]> dividedMonths = new ArrayList<>();
        for (int i = 0; i < months.size(); i++) {
            String item = months.get(i);
            String b, e;
            DateTime sd = new DateTime(item);
            if (i == 0)
                b = beginDate;
            else
                b = item + "-01";
            if (i == months.size() - 1)
                e = endDate;
            else
                e = item + "-" + sd.dayOfMonth().getMaximumValue();
            String[] date = new String[2];
            date[0] = b; //开始日期
            date[1] = e; //截止日期
            dividedMonths.add(date);
        }
        return dividedMonths;
    }
}
